import { Byte } from '../../api/io/Byte';
import { HashMap } from '../../api/struct/HashMap';
import { Pet } from './Pet';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**宠物管理属性枚举*/
export const enum E_PetManager {
	/**背包等级*/
	BAG_LEVEL = 0,
	/**宠物表*/
	PET = 1,
	/**出战宠物<id, pos> pos从1开始，0代表没上*/
	FIGHTING = 2,
	/**拥有的配置id*/
	OWNED = 3,
	/**枚举数量*/
	EnumCount = 4
}


/**宠物管理*/
export class PetManager {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_PET_MANAGER_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_PET_MANAGER_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: PetManager[] = [];

	/**创建入口*/
	public static create(json?: string): PetManager {
		const c = this.POOL.pop() || new PetManager();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**背包等级 (uint16)*/
	protected _bagLevel: number;
	/**宠物表*/
	protected _pet: HashMap<number, Pet> = null;
	/**出战宠物<id, pos> pos从1开始，0代表没上 (uint32, int8)*/
	protected _fighting: HashMap<number, number> = null;
	/**拥有的配置id (uint32)*/
	protected _owned: number[] = [];


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (PetManager.POOL.indexOf(this) === -1) {
			PetManager.POOL.push(this);
		}
	}

	/**背包等级*/
	public get bagLevel() {
		return this._bagLevel;
	}


	/**背包等级*/
	public set bagLevel(v: number) {
		this._bagLevel = v;
	}


	/**设置宠物表*/
	public putPet(k: number, v: Pet): Pet {
		const ov = this._pet.put(k, v);
		return ov;
	}


	/**获取宠物表*/
	public getPet(k: number) {
		return this._pet.get(k);
	}


	/**删除宠物表*/
	public removePet(k: number, autoDestroy = false): Pet {
		const ov = this._pet.remove(k);
		if (autoDestroy && ov) {
			ov.destroy();
		}
		return ov;
	}


	/**获取宠物表映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getPetKeys(): number[] {
		return this._pet.getKeys();
	}


	/**获取宠物表映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getPetValues(): Pet[] {
		return this._pet.getValues();
	}


	/**清空宠物表映射表*/
	public clearPetMap(autoDestroy = false): void {
		const ks = this._pet.getKeys();
		for (let i = ks.length - 1; i >= 0; i--) {
			this.removePet(ks[i], autoDestroy);
		}
	}


	/**设置出战宠物<id, pos> pos从1开始，0代表没上*/
	public putFighting(k: number, v: number): number {
		const ov = this._fighting.put(k, v);
		return ov || 0;
	}


	/**获取出战宠物<id, pos> pos从1开始，0代表没上*/
	public getFighting(k: number) {
		return this._fighting.get(k) || 0;
	}


	/**删除出战宠物<id, pos> pos从1开始，0代表没上*/
	public removeFighting(k: number): number {
		const ov = this._fighting.remove(k);
		return ov || 0;
	}


	/**获取出战宠物<id, pos> pos从1开始，0代表没上映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getFightingKeys(): number[] {
		return this._fighting.getKeys();
	}


	/**获取出战宠物<id, pos> pos从1开始，0代表没上映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getFightingValues(): number[] {
		return this._fighting.getValues();
	}


	/**清空出战宠物<id, pos> pos从1开始，0代表没上映射表*/
	public clearFightingMap(): void {
		this._fighting.clear();
	}


	/**增加拥有的配置id*/
	public addOwned(v: number): void {
		if (this._owned.indexOf(v) === -1) {
			this._owned.push(v);
		}
	}

	/**删除拥有的配置id*/
	public removeOwned(v: number): void {
		const idx = this._owned.indexOf(v);
		if (idx >= 0) {
			this._owned.splice(idx, 1);
		}
	}

	/**获取拥有的配置id列表*/
	public getOwnedList(): number[] {
		return this._owned;
	}


	/**通过枚举获取值*/
	public getV(k: E_PetManager): any {
		switch (k) {
			case E_PetManager.BAG_LEVEL: return this._bagLevel;
			case E_PetManager.PET: return this._pet;
			case E_PetManager.FIGHTING: return this._fighting;
			case E_PetManager.OWNED: return this._owned;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_PetManager, v: any): void {
		switch (k) {
			case E_PetManager.BAG_LEVEL: this._bagLevel = v; break;
			case E_PetManager.PET: this._pet = v; break;
			case E_PetManager.FIGHTING: this._fighting = v; break;
			case E_PetManager.OWNED: this._owned = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//背包等级
		this._bagLevel = 0;
		//宠物表
		if (this._pet) {
			const list = this._pet.getValues();
			for (let i = 0, len = list.length; i < len; i++) {
				list[i].destroy();
			}
			this._pet.clear();
		}
		else {
			this._pet = new HashMap<number, Pet>();
		}
		//出战宠物<id, pos> pos从1开始，0代表没上
		if (this._fighting) {
			this._fighting.clear();
		}
		else {
			this._fighting = new HashMap<number, number>();
		}
		//拥有的配置id
		if (this._owned) {
			this._owned.length = 0;
		}
		else {
			this._owned = [];
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._bagLevel) {
			json.bagLevel = this._bagLevel;
		}
		if (this._pet.size() > 0) {
			const ks = this._pet.getKeys();
			const vs = this._pet.getValues();
			const list: string[] = [];
			for (let i = 0, len = vs.length; i < len; i++) {
				list[i] = vs[i].stringify(false);
			}
			json.pet = [ks, list];
		}
		if (this._fighting.size() > 0) {
			const ks = this._fighting.getKeys();
			const vs = this._fighting.getValues();
			json.fighting = [ks, vs];
		}
		if (this._owned) {
			json.owned = this._owned;
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.bagLevel) {
			this._bagLevel = json.bagLevel;
		}
		if (json.pet) {
			const ks: number[] = json.pet[0] || (json.pet.getKeys ? json.pet.getKeys() : null);	//对象可能是json或者结构体
			const vs: string[] = json.pet[1] || (json.pet.getValues ? json.pet.getValues() : null);
			if (ks && vs && ks.length === vs.length) {
				for (let i = 0, len = vs.length; i < len; i++) {
					this._pet.put(ks[i], Pet.create(vs[i]));
				}
			}
		}
		if (json.fighting) {
			const ks: number[] = json.fighting[0];
			const vs: number[] = json.fighting[1];
			if (ks && vs && ks.length === vs.length) {	//json
				this._fighting.setKeyAndValueList(ks, vs);
			}
			else if (json.fighting.getKeys && json.fighting.getValues) {	//结构体
				const ks2 = json.fighting.getKeys();
				const vs2 = json.fighting.getValues();
				if (ks2 && vs2 && ks2.length === vs2.length) {
					for (let i = 0, len = vs2.length; i < len; i++) {
						this._fighting.put(ks2[i], vs2[i]);	//重新添加，防止数据公用后被释放导致bug
					}
				}
			}
		}
		if (json.owned) {
			this._owned = json.owned;
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeUint16(this._bagLevel);
		//宠物表
		{
			const ks = this._pet.getKeys();
			const vs = this._pet.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint32(ks[i]);
				vs[i].toBytes(byte);
			}
		}
		//出战宠物<id, pos> pos从1开始，0代表没上
		{
			const ks = this._fighting.getKeys();
			const vs = this._fighting.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint32(ks[i]);
				byte.writeInt8(vs[i]);
			}
		}
		//拥有的配置id
		{
			const list = this._owned;
			if (list) {
				byte.writeUint32(list.length);
				for (let i = 0, len = list.length; i < len; i++) {
					byte.writeUint32(list[i]);
				}
			}
			else {
				byte.writeUint32(0);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._bagLevel = byte.readUint16();
		//宠物表
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint32();
				const v = Pet.create();
				v.fromBytes(byte);
				this._pet.put(k, v);
			}
		}
		//出战宠物<id, pos> pos从1开始，0代表没上
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint32();
				const v = byte.readInt8();
				this._fighting.put(k, v);
			}
		}
		//拥有的配置id
		{
			const len = byte.readUint32();
			for (let i = 0; i < len; i++) {
				this._owned[i] = byte.readUint32();
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): PetManager {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = PetManager.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = PetManager.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//背包等级
			if (idx === E_PetManager.BAG_LEVEL) {
				const oldv = this._bagLevel;
				this._bagLevel = us[i + 1];
				IAsync.dispatch(eventID, idx, this._bagLevel, oldv);
				i += 2;
				continue;
			}

			//宠物表
			if (idx === E_PetManager.PET) {
				const k: number = us[i + 1];
				const ctrl: number = us[i + 2];
				if (ctrl === 0) {
					const oldv = this.removePet(k);
					if (oldv) {
						oldv.destroy()
					}
				}
				else if (ctrl === 1) {
					const newv = Pet.create(us[i + 3]);
					const oldv = this.putPet(k, newv);
					if (oldv) {
						oldv.destroy()
					}
				}
				else {
					const curv = this.getPet(k);
					if (curv) {
						curv.processUpdate(us[i + 3]);
					}
					else {
						console.error('PetManager Pet is not exist when update! k = ' + k);
					}
				}
				IAsync.dispatch(eventID, idx, k, ctrl);
				i += ctrl === 0 ? 3 : 4;
				continue;
			}

			//出战宠物<id, pos> pos从1开始，0代表没上
			if (idx === E_PetManager.FIGHTING) {
				const k: number = us[i + 1];
				const newv :number = us[i + 2];
				const oldv = this.putFighting(k, newv);
				IAsync.dispatch(eventID, idx, k, newv, oldv);
				i += 3;
				continue;
			}
			//拥有的配置id
			if (idx === E_PetManager.OWNED) {
				const c: number = us[i + 1];
				const v: number = us[i + 2];
				if (c === 0) {
					const idx = this._owned.indexOf(v);
					if (idx >= 0) {
						this._owned.splice(idx, 1);
					}
				}
				else {
					const idx = this._owned.indexOf(v);
					if (idx === -1) {
						this._owned.push(v);
					}
				}
				IAsync.dispatch(eventID, idx, c, v);
				i += 3;
				continue;
			}

			console.error('[Struct Data] can not find enum in PetManager with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: PetManager): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._bagLevel !== other._bagLevel) {
			updates.push(E_PetManager.BAG_LEVEL, this._bagLevel);
		}

		//宠物表
		{
			const idx = E_PetManager.PET;
			const ks1 = this._pet.getKeys();
			const ks2 = other._pet.getKeys();
			const rs = MathUtils.intersectSortedArray(ks1, ks2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getPet(k);
					const oldv = other.getPet(k);
					const ui = newv.getCompareInfo(oldv);
					if (ui && ui.length > 0) {
						updates.push(idx, k, 2, ui);
					}
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getPet(k);
					updates.push(idx, k, 1, newv.stringify(false));
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		//出战宠物<id, pos> pos从1开始，0代表没上
		{
			const idx = E_PetManager.FIGHTING;
			const ks1 = this._fighting.getKeys();
			const ks2 = other._fighting.getKeys();
			const vs1 = this._fighting.getValues();
			const vs2 = other._fighting.getValues();
			const rs = MathUtils.intersectSortedArray(ks1, ks2, vs1, vs2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getFighting(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getFighting(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		//拥有的配置id
		{
			const idx = E_PetManager.OWNED;
			const rs = MathUtils.intersectSortedArray(this._owned, other._owned);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					const oldv = list[i];
					updates.push(idx, 0, oldv);
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(PetManager.TOTAL_EVENT_ID, this.getV(0));
	}

}
